#!/bin/sh

############################################################################################
# THIS MODULE INCLUDES ALL THE ACTIONS INTENDED FOR THE MANAGEMENT OF LISTS AND SINGLE PAGES
############################################################################################

_clean_lists_and_queries() {
	# Remove references to URLs, "-a" elements and limit message length to a maximum of 80 characters in "-l" and "-q"
	sed -E 's#(http|https|ftp)://[^ ]*##g; s#(SITE|SOURCE):##g'
}

_download_markdown() {
	local disk_usage=""
	local app_version=""
	local markdown_url="$AMCATALOGUEMARKDOWNS/${1}.md"
	local cache_dir="$AMCACHEDIR/about"
	local app_status=" STATUS: NOT INSTALLED"
	local package_name=${1^^}
	if curl -o /dev/null -sIf "$markdown_url"; then
		mkdir -p "$cache_dir" && wget -q "$markdown_url" -P "$cache_dir"
		sed -i '1,${ /^\s*#/ d; /^\s*!/ d; /\[Applications]/d; /\ --- /d; /\ | - | /d; /\!\[/d; }' "$cache_dir/$1.md"
		sed -i '$!N;s/^\s*\n\s*$//;P;D' "$cache_dir/$1.md"
		printf ' PACKAGE: %s\n' "$package_name"
		if [ -f "$APPSPATH/$1/remove" ]; then
			disk_usage=$(du -sm "$APPSPATH/$1" | cut -f1)
			app_version=$(cat "$AMCACHEDIR"/version-args 2>/dev/null | grep -w " ◆ $1	|" | sed 's:.*|	::')
			app_status=$(echo -e " STATUS: INSTALLED, ABOUT $disk_usage MB OF DISK SPACE IN USE\n VERSION: $app_version")
		fi
		printf '%s\n' "$app_status"
		cat -s "$cache_dir/$1.md"
		if [ -z "$cache_dir" ]; then
			exit 1
		fi
		rm -R -f "$cache_dir"
		
	else
		printf ' "%s" IS NOT A VALID ARGUMENT\n' "$package_name"
	fi
}

_generate_3rd_party() {
	local disk_usage=""
	local app_version=""
	local app_status=" STATUS: NOT INSTALLED"
	local package_name=${1^^}
	if grep -q "◆ $arg : " "$AMPATH/$arch-apps"; then
		printf ' PACKAGE: %s\n' "$arg" | tr a-z A-Z
		if [ -f "$APPSPATH/$1/remove" ]; then
			disk_usage=$(du -sm "$APPSPATH/$1" | cut -f1)
			app_version=$(cat "$AMCACHEDIR"/version-args 2>/dev/null | grep -w " ◆ $1	|" | sed 's:.*|	::')
			app_status=$(echo -e " STATUS: INSTALLED, ABOUT $disk_usage MB OF DISK SPACE IN USE\n VERSION: $app_version")
		fi
		printf '%s\n' "$app_status"
		grep "◆ $arg : " < "$AMPATH/$arch-apps" | cut -d':' -f2- | sed 's/^./\n /' | sed 's# SOURCE:#\n\n SOURCE:#g'
	else
		printf ' "%s" IS NOT A VALID ARGUMENT\n' "$package_name"
	fi
}

_download_lib() {
	local lib_name_upper=${1^^}
	printf "%s\n" " LIBRARY: $lib_name_upper"
	if [[ -f "$APPSPATH/$1/remove" ]]; then 
		local lib_path=$(grep "usr/local/lib" "$APPSPATH/$1/remove" | head -1)
		local disk_usage=$(du -sm "$lib_path" | cut -f1)

		if [[ "$disk_usage" -eq 0 ]]; then
			printf "%s\n" " STATUS: INSTALLED, LESS THAN 1 MB OF DISK SPACE IN USE"
		else
			printf "%s\n" " STATUS: INSTALLED, ABOUT $disk_usage MB OF DISK SPACE IN USE"
		fi
	else 
		printf "%s\n" " STATUS: NOT INSTALLED"
	fi
	echo ""
	grep "◆ $1 : " "$AMPATH/libs-list" | sed 's#.*:##' | sed 's/(/\n (/g'
	echo "" && echo " SITE/SOURCES:" && echo ""
	local site_source=$(wget -qO- "$APPSDB/$1" | grep -Eo "(http|https)://[a-zA-Z0-9./?=_%:-]*" | head -1)
	echo " $site_source"
	echo ""
}

_list() {
	LIBNUMBER=$(cat $APPSPATH/*/remove 2> /dev/null | grep "usr/local/lib" | wc -l)
	ITEMSNUMBER=$(cd $APPSPATH && find -name 'remove' -printf "%h\n" 2>/dev/null | sort -u | wc -l)
	if [ "$AMCLI" == am ]; then
		ITEMSNUMBER=$(("$ITEMSNUMBER"-1))
	fi
	APPSNUMBER=$(echo "$(("$ITEMSNUMBER" - "$LIBNUMBER"))")
	if test -f "$AMCACHEDIR"/version-args; then
		INSTALLED=$(cat "$AMCACHEDIR"/version-args 2>/dev/null | sort | sed 's/	|	/ /g' | grep -v "◆ am ")
		MESSAGE2="\n$INSTALLED\n"
	else
		_check_version
		INSTALLED=$(cat "$AMCACHEDIR"/version-args 2>/dev/null | sort | sed 's/	|	/ /g' | grep -v "◆ am ")
		MESSAGE2="\n$INSTALLED\n"
	fi

	wget -q --tries=10 --timeout=20 --spider https://github.com && _completion_lists
	if cat $APPSPATH/*/remove 2> /dev/null | grep -q "usr/local/lib"; then
		if [ "$LIBNUMBER" == 1 ]; then
			MESSAGE=$(echo " YOU HAVE INSTALLED $APPSNUMBER APPLICATIONS OUT OF $(grep -e "$" -c $AMPATH/$arch-apps) AVAILABLE, AND $LIBNUMBER LIBRARY")
		else
			MESSAGE=$(echo " YOU HAVE INSTALLED $APPSNUMBER APPLICATIONS OUT OF $(grep -e "$" -c $AMPATH/$arch-apps) AVAILABLE, AND $LIBNUMBER LIBRARIES")
		fi
	else
		MESSAGE=$(echo " YOU HAVE INSTALLED $APPSNUMBER APPLICATIONS OUT OF $(grep -e "$" -c $AMPATH/$arch-apps) AVAILABLE")
	fi
	echo -e "\n$MESSAGE\n$MESSAGE2\n LIST OF THE $(grep -e "$" -c $AMPATH/$arch-apps) APPLICATIONS AVAILABLE IN THE 'AM' REPOSITORY:\n\n$(cat $AMPATH/$arch-apps | _clean_lists_and_queries)\n" | less -I
	echo -e "\n$MESSAGE\n$MESSAGE2"
}

# Define functions
usage() {
	echo " USAGE: $AMCLI $1 [ARGUMENT]"
}

case "$1" in
	'-a'|'about')
		_online_check
		case $2 in
			'')
				echo " USAGE: $AMCLI $1 [ARGUMENT]"
				exit
				;;
		esac
		if ! test -f "$AMCACHEDIR"/version-args; then
			_check_version
		fi

		# Main logic
		if [ ! -f "$AMPATH/libs-list" ]; then
			wget -q "$LIBSLISTDB" -P "$AMPATH"
		fi

		# Skip the first argument which is not part of ARGS
		for arg in "${@:2}"; do
			if curl -o /dev/null -sIf "$AMCATALOGUEMARKDOWNS/${arg}.md" 1>/dev/null; then
				_download_markdown "$arg"
			elif grep -q "◆ $arg : " "$AMPATH/$arch-apps"; then
				_generate_3rd_party
			elif grep -q "◆ $arg : " "$AMPATH/libs-list"; then
				_download_lib "$arg"
			else
				printf '%s is not a valid argument\n' " $arg" | tr a-z A-Z
			fi
			printf "%s\n" "-----------------------------------------------------------------------"
		done
		;;

	'-l'|'list')
		_list
		;;

	'-q'|'query')
		case $2 in
			'')
				echo " USAGE: $AMCLI $1 [ARGUMENT]"
				exit
				;;
		esac
		wget -q --tries=10 --timeout=20 --spider https://github.com && _completion_lists
		if [ "$2" = --pkg ]; then
			ARGS=$(echo "$@" | cut -f3- -d ' ' | sed 's/ /, /g')
			echo -e "\n Search results for packages: $ARGS\n" | tr a-z A-Z
			grep -i -E "$(echo "$@" | cut -f3- -d ' ' | tr -s ' ' '|')" "$AMPATH/$arch-apps" --color=always | _clean_lists_and_queries
			grep -i -E "$(echo "$@" | cut -f3- -d ' ' | tr -s ' ' '|')" "$AMPATH/libs-list" --color=always | _clean_lists_and_queries
			echo ""
			exit 0
		fi
		ARGS=$(echo "$@" | cut -f2- -d ' ')
		echo -e "\n Search results for \"$ARGS\":\n" | tr a-z A-Z
		PATTERN="$(echo "$@" | cut -f2- -d ' ' | sed 's/ /(?=.*/g; s/$/)/g; s/(/)(/g; s/^/(?=.*/g;')"
		grep -P -i "$PATTERN" "$AMPATH/$arch-apps" | _clean_lists_and_queries
		grep -P -i "$PATTERN" "$AMPATH/libs-list" | _clean_lists_and_queries
		echo ""
		exit 0
		;;
esac
